import { combineReducers } from 'redux'
import {
    AUTH_SUCCESS,
    ERROR_MSG,
    UPDATE_USER_SUCCESS,
    UPDATE_USER_FAILED,
    GET_USER_SUCCESS,
    GET_USER_FAILED,
    RECEIVE_USER_LIST,
    RECEIVE_CHAT_MSG_LIST,
    RECEIVE_MSG,
    RECEIVE_READ_MSG
} from './action-type'
import { getRedirectTo } from '../utils'

const initUser={
    username:'',
    header:'',
    userType:'',
    msg:'',
    redirectTo:''
}

function user(state = initUser,action) {
    switch (action.type) {
        case AUTH_SUCCESS:
            const { userType, header } = action.data
            return { ...state, ...action.data,redirectTo:getRedirectTo(userType, header) }
        case ERROR_MSG:
            return { ...state, msg:action.data }
        case UPDATE_USER_SUCCESS:
            return action.data
        case UPDATE_USER_FAILED:
            return {...initUser,msg:action.data}
        case GET_USER_SUCCESS:
            return action.data
        case GET_USER_FAILED:
            return {...initUser,msg:action.data}
        default:
            return state
    }


}

let initUserList = []

function userList(state = initUserList, action) {

    switch (action.type) {
        case RECEIVE_USER_LIST:
            return action.data
        default:
            return state

    }
}

const initChatMsg = {
    users:{},
    chatMsgs:[],
    unReadCount:0
}

function chat(state=initChatMsg,action) {
    switch (action.type) {
        case RECEIVE_CHAT_MSG_LIST:
            const { users,chatMsgs,userId } = action.data
            return {
                users,
                chatMsgs,
                unReadCount:chatMsgs.reduce((preTotal,msg) => preTotal + (!msg.read && msg.to === userId ?1:0) ,0)
            }
        case RECEIVE_MSG:
            const { msg } = action.data
            return {
                users:state.users,
                chatMsgs:[...state.chatMsgs,action.data.msg],
                unReadCount:state.unReadCount + ( !msg.read && msg.to === action.data.userId ? 1: 0 )
            }
        case RECEIVE_READ_MSG:
            const { from,to,count } = action.data

            return {
                users:state.users,
                unReadCount:state.unReadCount - count,
                chatMsgs: state.chatMsgs.map(msg=>{
                    if (msg.from === from && msg.to === to && !msg.read ){
                        return { ...msg, read:true }
                    } else {
                        return msg
                    }
                })
            }
        default:
            return state
    }
}



export default combineReducers({
    user,
    userList,
    chat
})